import axios from 'axios'
import { getLocal } from '@/lib/utils'
import router from '@/router'
// 创建一个 axios 实例
const $http = axios.create({
  // baseURL: '/api', // 所有的请求地址前缀部分
  timeout: 6000, // 请求超时时间毫秒
})

// 添加请求拦截器
$http.interceptors.request.use(
  config => {
    const token = getLocal('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

// 添加响应拦截器
$http.interceptors.response.use(
  response => {
    const dataAxios = response.data
    return dataAxios
  },
  error => {
    const response = error.response
    const message = response?.data?.message || '请求失败'
    if (response.status === 401) {
      ElMessageBox.confirm('登录过期，请重新登录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        router.push('/login')
      })
    } else {
      ElMessage({
        message,
        type: 'error',
      })
    }
    console.log(error.toJSON())
    return Promise.reject(error)
  },
)

//定义泛型
export const get = <T, U>(url: string, data?: T) => $http.get<U>(url, { params: data })
export const post = <T, U>(url: string, data?: T) => $http.post<U>(url, data)
export const postForm = <T, U>(url: string, data?: T) => $http.patchForm<U>(url, data)
export const del = <T, U>(url: string, data?: T) => $http.delete<U>(url, { params: data })
export const patch = <T, U>(url: string, data?: T) => $http.patch<U>(url, data)
